package com.wang.project.pay.zfb;

import cn.hutool.json.JSONUtil;
import com.wang.project.model.modle.PayModel;
import com.wang.project.utils.CommonUtils;
import com.wang.project.common.BaseResponse;
import com.wang.project.common.ResultUtils;
import com.wang.project.model.entity.User;
import com.wang.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * 此接口为测试支付接口，不是真正支付的入口
 */
@Controller
@RequestMapping("/AlipayFaceToFace")
@Slf4j
public class AlipayFaceToFaceController {

    @Resource
    private UserService userService;

    @Resource
    AlipayFaceToFaceService alipayFaceToFaceService;

    /**
     * 支付统一入口，先获取支付二维码
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/getAlipayInfo")
    @ResponseBody
    public BaseResponse<ZFBPreorderActionVO> getAlipayInfo(HttpServletRequest request, HttpServletResponse response) {
        User loginUser = userService.getLoginUser(request);
        log.info("AlipayFaceToFaceController getAlipayInfo loginUser: " + JSONUtil.toJsonStr(loginUser));
        PayModel payModel = new PayModel();
        payModel.setUser(loginUser);
        payModel.setPayCount(1);
        payModel.setAmount(0.01);
        payModel.setSubject("测试支付标题");
        payModel.setOrderNumber(CommonUtils.getAlipayOutTradeNo("test"));
        ZFBPreorderActionVO zfbPreorderActionVO = alipayFaceToFaceService.ZFBPreorderAction(request, response, payModel);
        return ResultUtils.success(zfbPreorderActionVO);
    }


    /**
     * 查看支付状态
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/findZFB_tradeAction", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> findZFB_tradeAction(@RequestBody String outTradeNo, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> zfbTradeAction = alipayFaceToFaceService.findZFB_tradeAction(outTradeNo, request, response);
        return zfbTradeAction;
    }

    /**
     * 支付回调函数（当用户支付成功之后，支付宝会自动调用该方法）
     * 此接口需要可以被外网访问而且必须是POST请求，并且注意拦截器是否拦截（如果被被您的登录拦截器拦截了，支付宝就无法访问此方法了）
     *
     * @param request
     * @param response
     */
    @RequestMapping("/ZFBcallback")
    public void ZFBcallback(HttpServletRequest request, HttpServletResponse response) {
        alipayFaceToFaceService.ZFBcallback(request, response);
    }
}